import json
import redis
from ronglian_sms_sdk import SmsSDK
from flask import current_app


class SendSMS:
    sdk = None
    rds = None

    def __init__(self):
        accId = current_app.config["ACCOUNT_SID"]
        accToken = current_app.config["AUTH_TOKEN"]
        appId = current_app.config["APPID"]
        self.sdk = SmsSDK(accId, accToken, appId)
        self.rds = redis.Redis(host=current_app.config["REDIS_HOST"], port=current_app.config["REDIS_PORT"],
                               password=current_app.config["REDIS_PASSWORD"])  # redis连接对象

    def send_sms(self, mobile, datas):
        '''
        发送短信验证码
        :param mobile: 手机号
        :param datas: 模板参数，元组
        :return: bool
        '''
        tid = current_app.config["TID"]
        # 【云通讯】您的验证码是{1}，请于{2}分钟内正确输入。
        resp = self.sdk.sendMessage(tid, mobile, datas)  # resp的类型是字符串
        resp = json.loads(resp)  # 解析json字符串

        # 存到redis
        key = "sms_" + mobile
        self.rds.set(key, datas[0], ex=int(datas[1]) * 60)

        if resp["statusCode"] == "000000":
            return True
        else:
            return False

    def ver_code(self, mobile, code):
        '''
        校验验证码
        :param mobile: 手机号
        :param code: 验证码
        :return: bool
        '''
        key = "sms_" + mobile
        res = self.rds.get(key)  # 返回值是字节类型 或 None
        if not res:
            return False

        sys_code = res.decode()

        if sys_code != code:
            return False
        else:
            return True


if __name__ == '__main__':
    from app import app

    with app.app_context():
        s = SendSMS()
        r = s.send_sms("15238002676", ("6666", "5"))
        print(r)

        r = s.ver_code("15238002676", "6677")
        print(r)
